package ch.ffhs.esma.bunk_weiss.notepad;

/**
 * @author: Tobias Weiss/Julian Bunk
 * @Date: 04.01.2015
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class SynchronizeClient extends Activity implements OnClickListener {

	private boolean CONTINUE_READ_WRITE = true;
	private TextView state;
	private TextView input;
	private TextView output;
	private int nbr = 0;
	
	DatabaseAdapter dbHelper;
	DataBaseHandler handler;
	Cursor cursor;
	SQLiteDatabase database;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.synchronize_note_activity);

		// Back to Main-Menu
		View verwerfen = findViewById(R.id.backtomain);
		verwerfen.setOnClickListener(this);

		registerReceiver(discoveryResult, new IntentFilter(
				BluetoothDevice.ACTION_FOUND));

		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

		state = (TextView) findViewById(R.id.state);

		if (adapter != null && adapter.isDiscovering()) {
			adapter.cancelDiscovery();
			state.setText("cancelDiscovery(.....)");
		}

		if (adapter != null) {
			adapter.startDiscovery();
			state.setText("startDiscovery(.....)");
		} else {
			state.setText("adapter == null");
		}

		input = (TextView) findViewById(R.id.receive);
		input.setText("Read: ");
		output = (TextView) findViewById(R.id.send);
		output.setText("Sent: ");
	}

	//public void onSend(View v){
	public void onSend(){
		dbHelper = new DatabaseAdapter(this);
		dbHelper.open();
		database = handler.getReadableDatabase();
		//database.beginTransaction()
		String databaseString = database.toString();
		
		//String msg = "Message From Client " + (nbr++) + "\n";
		String msg = databaseString + "\n";
		System.out.println(msg);
		/*
		try {
			output.setText("Sent: " + msg);
			os.write(msg);
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			unregisterReceiver(discoveryResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (socket != null) {
			try {
				is.close();
				os.close();
				socket.close();
				CONTINUE_READ_WRITE = false;
			} catch (Exception e) {
			}
		}
	}

	private BluetoothSocket socket;
	private OutputStreamWriter os;
	private InputStream is;
	private BluetoothDevice remoteDevice;
	private BroadcastReceiver discoveryResult = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			android.util.Log.e("TrackingFlow", "WWWTTTFFF");
			unregisterReceiver(this);
			remoteDevice = intent
					.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			new Thread(reader).start();
		}
	};

	private Runnable reader = new Runnable() {

		@Override
		public void run() {
			try {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						state.setText("TrackingFlow  Found: "
								+ remoteDevice.getName());
					}
				});

				UUID uuid = UUID
						.fromString("4e5d48e0-75df-11e3-981f-0800200c9a66");
				socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
				socket.connect();

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						state.setText("TrackingFlow  Connected...");
					}
				});
				os = new OutputStreamWriter(socket.getOutputStream());
				is = socket.getInputStream();

				int bufferSize = 1024;
				int bytesRead = -1;
				byte[] buffer = new byte[bufferSize];
				// Keep reading the messages while connection is open...
				while (CONTINUE_READ_WRITE) {
					android.util.Log.e("TrackingFlow", "WWWTTTFFF3wwwww4243");
					final StringBuilder sb = new StringBuilder();
					bytesRead = is.read(buffer);
					if (bytesRead != -1) {
						String result = "";
						while ((bytesRead == bufferSize)
								&& (buffer[bufferSize - 1] != 0)) {
							result = result
									+ new String(buffer, 0, bytesRead - 1);
							bytesRead = is.read(buffer);
						}
						result = result + new String(buffer, 0, bytesRead - 1);
						sb.append(result);
					}

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							input.setText("Read: " + sb.toString());
						}
					});

				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public void onClick(View arg0) {
		if (arg0.getId() == R.id.backtomain) {

			// define a new Intent for the Home Activity
			Intent intent = new Intent(this, Home.class);

			// start the Home Activity
			this.startActivity(intent);
			finish();
		}
		//start the synchronisation
		if (arg0.getId() == R.id.syncButton) {
			onSend();
		}
	}

}
